﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MemoLib;
using MemoLib.Tasks;

namespace UI
{
    public partial class FrmTaskList : Form
    {
        private List<Form> popupForms = new List<Form>();
        public FrmTaskList()
        {
            InitializeComponent();
            this.ShowInTaskbar = false;
            timer.Interval = ConfigOperator.GetIntervalMinutes() * 1000 * 60;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            ShowMessage();
        }

        private void ShowMessage()
        {
            TimeMother.Execute();
            // 只有消息的时候才需要显示窗体
            if (ExecuteContext.MessageBusket.Count > 0 && this.ifAlertMessage)
            {
                frmMessage frm = new frmMessage();
                frm.ShowMessage();
            }
        }

        System.Windows.Forms.Timer timer = new Timer();

        private const string LABEL_REMIND = "当前状态：提醒状态";
        private const string LABEL_SILENCE = "当前状态：安静状态";
        private const string BTN_SETREMIND = "设置为提醒状态";
        private const string BTN_SETSILENCE = "设置为安静状态";
        private void FrmTaskList_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            SetModeConfigButtonAndLabel();

            this.ShowMessage();
            
            BindTasks();
        }

        private void SetModeConfigButtonAndLabel()
        {
            this.lblMode.Text = ifAlertMessage ? LABEL_REMIND : LABEL_SILENCE;
            this.btnMode.Text = ifAlertMessage ? BTN_SETSILENCE : BTN_SETREMIND;
        }

        private bool ifAlertMessage
        {
            get {
                return ConfigOperator.GetRemindFlg() == "1";
            }
        }

        private void BindTasks()
        {
            ExcelOperator eop = new ExcelOperator(ConfigOperator.GetExcelPath());
            eop.OpenConn();
            DataTable dt1 = eop.GetTableFromExcelSheet("Sheet1");
            this.dgOnce.DataSource = dt1;
            DataTable dt2 = eop.GetTableFromExcelSheet("Sheet2");
            this.dgCycle.DataSource = dt2;
            DataTable dt3 = eop.GetTableFromExcelSheet("Sheet3");
            this.dgTodoList.DataSource = dt3;
            eop.CloseConn();
        }

        /// <summary>
        /// 窗体最小化后，隐藏，任务栏图标显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmTaskList_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.Visible = true;
            }
            // 每次窗体重新弹出，都重新检索一下
            else
            {
                BindTasks();
            }
        }
    
        /// <summary>
        /// 刷新页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            BindTasks();
        }

        /// <summary>
        /// 显示今天信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTodayTask_Click(object sender, EventArgs e)
        {
            BindTasks(); // 在显示当天任务之前先更新一下DataGridView，因为对于任务判断是否为当天的数据取自gridview
            frmTodayTask frm = new frmTodayTask(this.dgOnce, this.dgCycle);
            HandlePopupFormCreate(frm);
            frm.ShowDialog();
        }

        #region 一次性任务
        private void dgOnce_DoubleClick(object sender, EventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;

            DataGridViewCellCollection cells = dgv.SelectedRows[0].Cells;
            OnceTaskCard card = Utility.ConvertCellToOnceTaskCard(cells);

            frmOnceCreateUpdateTask frm = new frmOnceCreateUpdateTask(card);
            HandlePopupFormCreate(frm);
            frm.ShowDialog();
            // 刷新页面
            BindTasks();
        }

        private void UpdateCycleTask(DataGridViewCellCollection cells)
        {
            CycleTaskCard card = Utility.ConvertCellToCycleTask(cells);

            frmCycleCreateUpdateTask frm = new frmCycleCreateUpdateTask(card, OperationMode.Update);
            HandlePopupFormCreate(frm);
            frm.ShowDialog();
            // 刷新页面
            BindTasks();
        }

        /// <summary>
        /// 为弹出窗体指定关闭窗体事件（可以在弹出窗体关闭的时候从列表中删除），并将其放入到PopupForms列表中（这样防止主窗体在弹出页面获得焦点的时候最小化）
        /// </summary>
        /// <param name="pPopupForm"></param>
        private void HandlePopupFormCreate(Form pPopupForm)
        {
            pPopupForm.FormClosed += new FormClosedEventHandler(frm_FormClosed);
            this.popupForms.Add(pPopupForm);
        }

        /// <summary>
        /// 弹出窗体关闭的时候要从popForms列表中删除，这样主窗体在失去焦点的时候可以最小化到Notify
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.popupForms.Remove((Form)sender);
            this.Focus();
        }

        private void btnCreateOnceTask_Click(object sender, EventArgs e)
        {
            CreateNewOnceTask();
        }

        private void create_Click(object sender, EventArgs e)
        {
            CreateNewOnceTask();
        }

        private void CreateNewOnceTask()
        {
            frmOnceCreateUpdateTask frm = new frmOnceCreateUpdateTask();
            HandlePopupFormCreate(frm);
            frm.ShowDialog();

            BindTasks();
        }

        int? clickRowIndex = 0;
        /// <summary>
        /// 通过右键菜单，设置一次性任务“完成”
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Once_Complete_Click(object sender, EventArgs e)
        {
            if (!clickRowIndex.HasValue)
            {
                return;
            }

            OnceTaskCard card = Utility.ConvertCellToOnceTaskCard(this.dgOnce.Rows[clickRowIndex.Value].Cells);
            OnceTask task = new OnceTask();
            task.Card = card;
            task.ComplateTask();

            this.BindTasks();
        }

        private void Once_Delete_Click(object sender, EventArgs e)
        {
            if (!clickRowIndex.HasValue)
            {
                return;
            }

            OnceTaskCard card = Utility.ConvertCellToOnceTaskCard(this.dgOnce.Rows[clickRowIndex.Value].Cells);
            OnceTask task = new OnceTask();
            task.Card = card;
            // task.DeleteTask();

            this.BindTasks();
        }
        #endregion

        #region 循环类任务
        /// <summary>
        /// 通过点击按钮创建创建循环类任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreateCycleTask_Click(object sender, EventArgs e)
        {
            CreateNewCycleTask();
        }

        /// <summary>
        /// 创建循环类任务
        /// </summary>
        private void CreateNewCycleTask()
        {
            frmCycleCreateUpdateTask frm = new frmCycleCreateUpdateTask(OperationMode.Create);
            HandlePopupFormCreate(frm);
            frm.ShowDialog();
            // 刷新页面
            BindTasks();
        }

        /// <summary>
        /// 通过右键菜单，创建循环类列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cycleMenu_Create_Click(object sender, EventArgs e)
        {
            CreateNewCycleTask();
        }

        /// <summary>
        /// 右键循环类任务列表，弹出菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                Point point = dgv.PointToClient(Cursor.Position);
                this.GetMenu(dgv.Name).Show(dgv, point);

                this.clickRowIndex = e.RowIndex;
            }
        }

        /// <summary>
        /// 基于GridView的名称获取右键菜单的对象
        /// </summary>
        /// <param name="pDgvName"></param>
        /// <returns></returns>
        private ContextMenuStrip GetMenu(string pDgvName)
        {
            ContextMenuStrip ret = null;
            switch (pDgvName)
            {
                case "dgOnce":
                    ret = onceMenu;
                    break;
                case "dgCycle":
                    ret = cycleMenu;
                    break;
                case "dgTodoList":
                    ret = todoListMenu;
                    break;
            }

            return ret;
        }

        /// <summary>
        /// 循环类任务的复制功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cycleMenu_Copy_Click(object sender, EventArgs e)
        {
            if (this.clickRowIndex.HasValue)
            {
                DataGridViewCellCollection cells = this.dgCycle.Rows[this.clickRowIndex.Value].Cells;

                CycleTaskCard card = Utility.ConvertCellToCycleTask(cells);

                frmCycleCreateUpdateTask frm = new frmCycleCreateUpdateTask(card, OperationMode.Copy);
                this.HandlePopupFormCreate(frm);
                frm.ShowDialog();
                // 刷新页面
                BindTasks();
            }
            else
            {
                MessageBox.Show("请选择一行！");
            }
        }

        /// <summary>
        /// 通过双击来修改循环类任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgCycle_DoubleClick(object sender, EventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;

            DataGridViewCellCollection cells = dgv.SelectedRows[0].Cells;
            UpdateCycleTask(cells);
        }
        #endregion

        private void todoListMenu_Complete_Click(object sender, EventArgs e)
        {
            if (!this.clickRowIndex.HasValue) return;

            TodoTask task = new TodoTask();
            Int64 id = Int64.Parse(this.dgTodoList.Rows[this.clickRowIndex.Value].Cells["ID"].Value.ToString());
            task.UpdateTodoTask(id);
            if (this.dgTodoList.Rows[this.clickRowIndex.Value].Cells["TaskType"].Value.ToString().ToLower() == "once")
            {
                OnceTask onceTask = new OnceTask();
                OnceTaskCard card = new OnceTaskCard();
                card.CardID = id;
                onceTask.Card = card;
                onceTask.ComplateTask();
            }

            this.BindTasks();
        }

        private void btnMode_Click(object sender, EventArgs e)
        {
            ConfigOperator.SetRemindFlg();
            SetModeConfigButtonAndLabel();
        }

        private bool flgAlert; // 标识是否当前为弹出系统对话框状态（如果是此状态，窗体不需要最小化）
        /// <summary>
        /// From失去焦点（不是因为弹出页面）的时候将会最小化到右下角的任务栏中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmTaskList_Deactivate(object sender, EventArgs e)
        {
            // 如果窗体是因为弹出页面(包括确认对话框）失去焦点，不最小化
            if (this.popupForms.Count > 0 || flgAlert) return;

            this.WindowState = FormWindowState.Minimized;
        }

        private void notify_Menu_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
            }
            else if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.notifyIcon1.Visible = false;
            }
        }

        /// <summary>
        /// 双击单项任务，将会在弹出的消息窗体显示任务，以及网址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgTodoList_DoubleClick(object sender, EventArgs e)
        {
            if (ExecuteContext.MessageBusket.Count == 0)
            {
                DataGridView dgv = (DataGridView)sender;
                DataGridViewCellCollection cells = dgv.SelectedRows[0].Cells;
                string taskInfo = cells["Context"].Value.ToString();
                ExecuteContext.MessageBusket.Add(taskInfo);
                frmMessage frm = new frmMessage();
                frm.IsForTodoList = true;
                HandlePopupFormCreate(frm);
                frm.ShowMessage();
                ExecuteContext.MessageBusket.Clear();
            }
            else {
                MessageBox.Show("消息篮子中有消息，稍后再试");
            }
        }

        /// <summary>
        /// 删除循环任务里面的一项（实际操作是更新“Status”字段为“Delete”）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cycleMenu_Delete_Click(object sender, EventArgs e)
        {
            this.flgAlert = true;
            if (MessageBox.Show("确定要删除？", "删除确认", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
            {
                this.flgAlert = false;
                return;
            }
            this.flgAlert = false;
            if (this.clickRowIndex.HasValue)
            {
                DataGridViewCellCollection cells = this.dgCycle.Rows[this.clickRowIndex.Value].Cells;

                CycleTaskCard card = Utility.ConvertCellToCycleTask(cells);
                ExcelOperator op = new ExcelOperator(ConfigOperator.GetExcelPath());
                op.OpenConn();
                op.DeleteRow(CommonData.CYCLETASK_SHEETNAME, card.CardID.ToString());
                op.CloseConn();
                // 刷新页面
                BindTasks();
            }
            else
            {
                MessageBox.Show("请选择一行！");
            }
        }
    }
}
